<?php
/**
 * Created by PhpStorm.
 * User: t
 * Date: 2024/6/8
 * Time: 10:11
 *
 * @copyright: ©2024 永州微聚商网络科技有限公司
 * @link: https://www.weijuyunke.com
 */

namespace app\home\controller;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use app\common\model\AmountLog;
use app\common\model\CheckUser;
use app\common\model\Config;
use app\common\model\FollowUser;
use app\common\model\Level;
use app\common\model\MessageTemplate;
use app\common\model\NoticeMessage;
use app\common\model\SmsMessage;
use app\common\model\UserChat;
use app\common\model\UserCommission;
use app\common\model\UserGzh;
use app\common\model\UserLevel;
use app\common\model\UserMessage;
use app\common\model\UserToken;
use app\common\model\UserXcx;
use app\common\model\VisitLog;
use app\Request;
use app\services\jwt\JwtService;
use app\services\wechat\Miniprogram;
use app\services\wechat\Offiaccount;
use dh2y\qrcode\QRcode;
use think\cache\driver\Redis;
use think\Exception;
use WeChatPay\Formatter;

class User
{

    public function testLogin(Request $request)
    {
        $param = $request->param();
        $user['phone'] = $param['phoneNumber'];
        $userModel = new \app\common\model\User();
        $userInfo = $userModel->where($user)->find();
        if (empty($userInfo)) {
            $levelModel = new Level();
            $levelInfo = $levelModel->where(['level' => 0])->find();
            $user['level_id'] = $levelInfo['id'];
            $user['level_name'] = $levelInfo['name'];

            $user['phone'] = $param['phoneNumber'];
            $user['nickname'] = $this->getRandCode(6);
            $user['avatar'] = "https://n8.weijuyunke.com/2024-05-27/b47f4202405271749247903.png";
            $user['invite_code'] = $this->getRandCode(6);
            $user['sex'] = 1;
            $user['register_ip'] = request()->ip();
            $user['create_time'] = time();
            $user['last_login_ip'] = request()->ip();
            $user['last_login_time'] = time();
            /*  $puserInfo = $userModel->where(['invite_code' => $param['invite']])->find();
              if ($puserInfo) {
                  $user['pid'] = $puserInfo['id'];
                  $user['pids'] = $puserInfo['pids'] . ',' . $puserInfo['id'];
              } else {
                  return error('分享链接有误');
              }*/
            $userModel->insert($user);
            $userInfo = $userModel->where($user)->find();
        }

        $jwt = new JwtService();
        $token = $jwt->getToken($userInfo['id'], 30);  //获取token
        $tokenConfig = ['uid' => $userInfo['id'], 'token' => $token, 'create_time' => time(),
            'effective_time' => time() + 60 * 60 * 24 * 30, 'login_ip' => $request->ip(), 'type' => 1];  //token配置信息  //token配置信息
        $tokenModel = new UserToken();
        $tokenModel->insert($tokenConfig);  //更新token
        $userInfo['token'] = $token;
        return success('登录', $userInfo);
    }

    function getXcxUserInfo(Request $request)
    {
        $param = $request->param();
        if (!isset($param['code']) || empty($param['code'])) {
            return error('请传入code');
        }
        $Miniprogram = new Miniprogram();
        $wechatInfo = $Miniprogram->getXcxUserInfo($param['code']);
        if (isset($wechatInfo['errcode'])) {
            return error($wechatInfo['errmsg']);
        }
        $userXcxModel = new UserXcx();
        $userXcxData['openid'] = $wechatInfo['openid'];
        if (isset($wechatInfo['unionid'])) {
            $userXcxData['unionid'] = $wechatInfo['unionid'];
        } else {
            return error('请绑定微信开放平台账号');
        }
        $info['is_new_user'] = 1;
        $userXcxInfo = $userXcxModel->where($userXcxData)->find();
        if (empty($userXcxInfo)) {
            $userGzhModel = new UserGzh();
            $userGzh = $userGzhModel->where(['unionid' => $wechatInfo['unionid']])->find();
            if ($userGzh) {
                $info['is_new_user'] = 0;
            } else {
                $info['is_new_user'] = 1;
            }
        } else {
            $info['is_new_user'] = 0;

        }
        $info['openid'] = $wechatInfo['openid'];
        $info['unionid'] = $wechatInfo['unionid'];
        return success('获取登录信息', $info);
    }

    function getGzhUserInfo(Request $request)
    {
        $param = $request->param();
        if (!isset($param['code']) || empty($param['code'])) {
            return error('请传入code');
        }
        $Offiaccount = new Offiaccount();
        $userWechatInfo = $Offiaccount->get_user_info($param['code']);
        if (isset($userWechatInfo['errcode'])) {
            return error($userWechatInfo['errmsg']);
        }
        if (empty($userWechatInfo['unionid'])) {
            return error('公众号未绑定到开发者平台');
        }
        $userGzhModel = new UserGzh();
        $userGzhInfo = $userGzhModel->where(['openid' => $userWechatInfo['openid']])->find();
        $userWechatInfo['is_new_user'] = 1;
        if ($userGzhInfo) {
            $userWechatInfo['is_new_user'] = 0;
        } else {
            $userXcxModel = new UserXcx();
            $userXcxInfo = $userXcxModel->where(['unionid' => $userWechatInfo['unionid']])->find();
            if ($userXcxInfo) {
                $userWechatInfo['is_new_user'] = 0;
            } else {
                $userWechatInfo['is_new_user'] = 1;
            }
        }
        return success('获取登录信息', $userWechatInfo);

    }

    public function updateAddress(Request $request)
    {
        $userModel = new \app\common\model\User();
        $param = $request->param();
        $user['longitude'] = $param['longitude'];
        $user['dimension'] = $param['dimension'];
        $longitude = number_format(doubleval($user['longitude']), 6);
        $latitude = number_format(doubleval($user['dimension']), 6);

        $gps = $latitude . ',' . $longitude;
        $params = array(
            'location' => $gps,
            'key' => Config::getConfigValue('tencent_map_key'),
        );
        $url = 'https://apis.map.qq.com/ws/geocoder/v1/';
        $url = $url . '?' . http_build_query($params, '', '&');
        $mapResult = json_decode(curlGet($url));
        if ($mapResult->status == 0) {
            $user['province_name'] = $mapResult->result->address_component->province;
            $user['city_name'] = $mapResult->result->address_component->city;
            $user['area_name'] = $mapResult->result->address_component->district;
            $user['address'] = $mapResult->result->address;
        }

        $userModel->where(['id' => $request->userInfo['id']])->update($user);
        return success('更新位置成功');
    }

    public function xLogin(Request $request)
    {
        $param = $request->param();
        $userXcxModel = new UserXcx();
        $userModel = new \app\common\model\User();
        $levelModel = new Level();
        $userGzhModel = new UserGzh();
        $useXcxInfo = $userXcxModel->where(['openid' => $param['openid']])->find();
        $user['is_online'] = 1;
        try {
            $userXcxModel->startTrans();
            if (empty($useXcxInfo)) { // 没用小程序登录过
                $userXcxModel->insert(['openid' => $param['openid'], 'unionid' => $param['unionid'], 'create_time' => time()]);
                $user['user_xcx_id'] = $userXcxModel->getLastInsID();
                $userGzh = $userGzhModel->where(['unionid' => $param['unionid']])->find();// 用户没用小程序注册过 查看是使用公众号注册过
                if ($userGzh) {
                    $userInfo = $userModel->where(['user_gzh_id' => $userGzh['id']])->find(); // 使用了公众号组成
                    if ($userInfo) { //
                        //  用公众号已经注册了，直接关联小程序生成的数据
                        $user['last_login_ip'] = request()->ip();
                        $user['last_login_time'] = time();
                        $userModel->where(['id' => $userInfo['id']])->update($user);
                        $userInfo['last_login_ip'] = $user['last_login_ip'];
                        $userInfo['last_login_time'] = $user['last_login_time'];
                    } else {
                      /*  if (isset($param['sms_code']) && !empty($param['sms_code'])){
                            $smsMessageModel = new SmsMessage();
                            $smsMessageInfo = $smsMessageModel->where(['phone' => $param['phoneNumber'], 'code' => $param['sms_code'],'is_use' => 0])
                                ->order('create_time', 'desc')->find();
                            if (empty($smsMessageInfo)) {
                                return error('无效验证码');
                            }
                            if ( time() > $smsMessageInfo['effective_time']   ) {
                                return error('验证码过期');
                            }
                            $smsMessageModel->where(['id' => $smsMessageInfo['id']])->update(['is_use' => 1]);
                        }*/
                        $levelInfo = $levelModel->where(['level' => 0])->find();
                        $user['level_id'] = $levelInfo['id'];
                        $user['level_name'] = $levelInfo['name'];
                      //  $user['phone'] = $param['phoneNumber'];
                        $user['nickname'] = $param['nickname'];
                     /*   $user['birthday'] = $param['birthday'];*/
                        $user['avatar'] = $param['avatarUrl'];
                        $user['sex'] = $param['sex'];
                        $user['invite_code'] = $this->getRandCode(6);
                        $user['register_ip'] = request()->ip();
                        $user['create_time'] = time();
                        $user['last_login_ip'] = request()->ip();
                        $user['last_login_time'] = time();
                        $user['pid']  = 0;
                        if (isset($param['invite']) && !empty($param['invite'])) {
                            $puserInfo = $userModel->where(['invite_code' => $param['invite']])->find();
                            if ($puserInfo) {
                                $user['pid'] = $puserInfo['id'];
                                $user['pids'] = $puserInfo['pids'] . ',' . $puserInfo['id'];
                            } else {
                                $userXcxModel->rollback();
                                return error('分享链接有误');
                            }
                        }
                        $userModel->insert($user);
                        $userId = $userModel->getLastInsID();
                        $userCommissionModel   =  new UserCommission();
                        $userCommissionModel-> newUserReward($userId,$user['pid']);


                        $userInfo = $userModel->where(['id' => $userId])->find();
                    }
                } else {
                  /*  if (isset($param['sms_code']) && !empty($param['sms_code'])){
                        $smsMessageModel = new SmsMessage();
                        $smsMessageInfo = $smsMessageModel->where(['phone' => $param['phoneNumber'], 'code' => $param['sms_code'],'is_use' => 0])
                            ->order('create_time', 'desc')->find();
                        if (empty($smsMessageInfo)) {
                            return error('无效验证码');
                        }
                        if ( time() > $smsMessageInfo['effective_time']   ) {
                            return error('验证码过期');
                        }
                        $smsMessageModel->where(['id' => $smsMessageInfo['id']])->update(['is_use' => 1]);
                    }*/
                    $levelInfo = $levelModel->where(['level' => 0])->find();
                    $user['level_id'] = $levelInfo['id'];
                    $user['level_name'] = $levelInfo['name'];
                    //$user['phone'] = $param['phoneNumber'];
                    $user['nickname'] = $param['nickname'];
                 /*   $user['birthday'] = $param['birthday'];*/
                    $user['avatar'] = $param['avatarUrl'];
                    $user['sex'] = $param['sex'];
                    $user['invite_code'] = $this->getRandCode(6);
                    $user['register_ip'] = request()->ip();
                    $user['create_time'] = time();
                    $user['last_login_ip'] = request()->ip();
                    $user['last_login_time'] = time();
                    $user['pid'] = 0;
                    if (isset($param['invite']) && !empty($param['invite'])) {
                        $puserInfo = $userModel->where(['invite_code' => $param['invite']])->find();
                        if ($puserInfo) {
                            $user['pid'] = $puserInfo['id'];
                            $user['pids'] = $puserInfo['pids'] . ',' . $puserInfo['id'];
                        } else {
                            $userXcxModel->rollback();
                            return error('分享链接有误');
                        }
                    }
                    $userModel->insert($user);
                    $userId = $userModel->getLastInsID();
                    $userCommissionModel   =  new UserCommission();
                    $userCommissionModel-> newUserReward($userId,$user['pid']);
                    $userInfo = $userModel->where(['id' => $userId])->find();
                }
            } else {
                $userInfo = $userModel->where(['user_xcx_id' => $useXcxInfo['id']])->find();
                $user['last_login_ip'] = request()->ip();
                $user['last_login_time'] = time();
                $userModel->where(['id' => $userInfo['id']])->update($user);
                $userInfo['last_login_ip'] = $user['last_login_ip'];
                $userInfo['last_login_time'] = $user['last_login_time'];
            }

            if ($userInfo['status'] != 1) {
                $userXcxModel->rollback();
                return error('账号状态有误,请联系管理员');
            }
            //根据用户id生成token
            $jwt = new JwtService();
            $token = $jwt->getToken($userInfo['id'], 365);  //获取token
            $tokenConfig = ['uid' => $userInfo['id'], 'token' => $token, 'create_time' => time(),
                'effective_time' => time() + 60 * 60 * 24 * 365, 'login_ip' => $request->ip(), 'type' => 1];  //token配置信息  //token配置信息
            $tokenModel = new UserToken();
            $tokenModel->insert($tokenConfig);  //更新token
            $userInfo['token'] = $token;
            $userXcxModel->commit();
            return success('登录成功', $userInfo);
        } catch (Exception $exception) {
            $userXcxModel->rollback();
            return error($exception->getMessage());
        }
    }

    public function gLogin(Request $request)
    {
        $param = $request->param();
        $levelModel = new Level();
        $userGzhModel = new UserGzh();

        $user['is_online'] = 1;
        $userModel = new \app\common\model\User();
        $userGzhInfo = $userGzhModel->where(['openid' => $param['openid']])->find();
        try {
            $userModel->startTrans();
            if (empty($userGzhInfo)) { //没用使用公众号注册过
                $userGzhData = ['openid' => $param['openid'], 'unionid' => $param['unionid'], 'create_time' => time()];
                $userGzhModel->insert($userGzhData);
                $userGzhId = $userGzhModel->getLastInsID();
                $user['user_gzh_id'] = $userGzhId;
                $userXcxModel = new UserXcx();
                $userXcxInfo = $userXcxModel->where(['unionid' => $param['unionid']])->find();
                if ($userXcxInfo) {
                    $userInfo = $userModel->where(['user_xcx_id' => $userXcxInfo['id']])->find();
                    if ($userInfo) { // 使用了 小程序注册
                        $user['last_login_ip'] = request()->ip();
                        $user['last_login_time'] = time();
                        $userModel->where(['id' => $userInfo['id']])->update($user);
                    } else {
                    /*    if (isset($param['sms_code']) && !empty($param['sms_code'])){
                            $smsMessageModel = new SmsMessage();
                            $smsMessageInfo = $smsMessageModel->where(['phone' => $param['phoneNumber'], 'code' => $param['sms_code'],'is_use' => 0])
                                ->order('create_time', 'desc')->find();
                            if (empty($smsMessageInfo)) {
                                return error('无效验证码');
                            }
                            if ( time() > $smsMessageInfo['effective_time']   ) {
                                return error('验证码过期');
                            }
                            $smsMessageModel->where(['id' => $smsMessageInfo['id']])->update(['is_use' => 1]);
                        }*/
                        $levelInfo = $levelModel->where(['level' => 0])->find();
                        $user['level_id'] = $levelInfo['id'];
                        $user['level_name'] = $levelInfo['name'];
                        $user['nickname'] = $param['nickname'];
                        $user['avatar'] = $param['headimgurl'];
                        $user['invite_code'] = $this->getRandCode(6);
                        $user['sex'] = $param['sex'];
                        $user['register_ip'] = request()->ip();
                        $user['create_time'] = time();
                        $user['last_login_ip'] = request()->ip();
                        $user['last_login_time'] = time();
                       // $user['phone'] = $param['phoneNumber'];
                      /*  $user['birthday'] = $param['birthday'];*/
                        $user['pid'] = 0;
                        if (isset($param['invite']) && !empty($param['invite'])) {
                            $puserInfo = $userModel->where(['invite_code' => $param['invite']])->find();
                            if ($puserInfo) {
                                $user['pid'] = $puserInfo['id'];
                                $user['pids'] = $puserInfo['pids'] . ',' . $puserInfo['id'];
                            } else {
                                $userModel->rollback();
                                return error('分享链接有误');
                            }
                        }
                        $userModel->insert($user);
                        $userId = $userModel->getLastInsID();
                        $userCommissionModel   =  new UserCommission();
                        $userCommissionModel-> newUserReward($userId,$user['pid']);
                        $userInfo = $userModel->where(['id' => $userId])->find();
                    }
                } else {
                /*    if (isset($param['sms_code']) && !empty($param['sms_code'])){
                        $smsMessageModel = new SmsMessage();
                        $smsMessageInfo = $smsMessageModel->where(['phone' => $param['phoneNumber'], 'code' => $param['sms_code'],'is_use' => 0])
                            ->order('create_time', 'desc')->find();
                        if (empty($smsMessageInfo)) {
                            return error('无效验证码');
                        }
                        if ( time() > $smsMessageInfo['effective_time']   ) {
                            return error('验证码过期');
                        }
                        $smsMessageModel->where(['id' => $smsMessageInfo['id']])->update(['is_use' => 1]);
                    }*/
                    $levelInfo = $levelModel->where(['level' => 0])->find();
                    $user['level_id'] = $levelInfo['id'];
                    $user['level_name'] = $levelInfo['name'];
                    $user['nickname'] = $param['nickname'];
                    $user['avatar'] = $param['headimgurl'];
                    $user['invite_code'] = $this->getRandCode(6);
                    $user['pid'] = 0;
                    if (isset($param['invite']) && !empty($param['invite'])) {
                        $puserInfo = $userModel->where(['invite_code' => $param['invite']])->find();
                        if ($puserInfo) {
                            $user['pid'] = $puserInfo['id'];
                            $user['pids'] = $puserInfo['pids'] . ',' . $puserInfo['id'];
                        } else {
                            $userModel->rollback();
                            return error('分享链接有误');
                        }
                    }
                    $user['sex'] = $param['sex'];
                    $user['register_ip'] = request()->ip();
                    $user['create_time'] = time();
                    $user['last_login_ip'] = request()->ip();
                    $user['last_login_time'] = time();
                  //  $user['phone'] = $param['phoneNumber'];
               /*     $user['birthday'] = $param['birthday'];*/
                    $userModel->insert($user);
                    $userId = $userModel->getLastInsID();
                    $userCommissionModel   =  new UserCommission();
                    $userCommissionModel-> newUserReward($userId,$user['pid']);
                    $userInfo = $userModel->where(['id' => $userId])->find();
                }
            } else {
                $user['last_login_ip'] = request()->ip();
                $user['last_login_time'] = time();
                $userModel->where(['user_gzh_id' => $userGzhInfo['id']])->update($user);
                $userInfo = $userModel->where(['user_gzh_id' => $userGzhInfo['id']])->find();

            }
            if ($userInfo['status'] != 1) {
                $userModel->rollback();
                return error('账号状态有误,请联系管理员');
            }
            $jwt = new JwtService();
            $token = $jwt->getToken($userInfo['id'], 365);  //获取token
            $tokenConfig = ['uid' => $userInfo['id'], 'token' => $token, 'create_time' => time(),
                'effective_time' => time() + 60 * 60 * 24 * 365, 'login_ip' => $request->ip(), 'type' => 1];  //token配置信息  //token配置信息
            $tokenModel = new UserToken();
            $tokenModel->insert($tokenConfig);  //更新token
            $userInfo['token'] = $token;
            $userModel->commit();
            return success('成功', $userInfo);
        } catch (Exception $exception) {
            $userModel->rollback();
            return error($exception->getMessage());
        }
    }

    function getPhone(Request $request)
    {
        $param = $request->param();
        $Miniprogram = new Miniprogram();
        $request = $Miniprogram->getPhone($param['code']);
        return success('手机号', $request);
    }

    protected function getRandCode($num = 6)
    {
        $chars = 'abcdefghijklmnpqrstuvwxyz123456789';
        $str = '';
        for ($i = 0; $i < $num; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        $userModel = new \app\common\model\User();
        $user = $userModel->where(['invite_code' => $str])->find();
        if ($user) {
            self::getRandCode($num);
        }
        return $str;
    }

    public function userInfo(Request $request)
    {
        $param = $request->param();
        if (isset($param['id']) && !empty($param['id'])) {
            $userModel = new \app\common\model\User();
            $userInfo = $userModel->where(['id' => $param['id']])->find();
            $checkUserModel = new CheckUser();
            $checkLog = $checkUserModel->where(['uid' => $request->userInfo['id'], 'check_uid' => $param['id'],'is_agree' => 2])->find();
           if ($checkLog){
               $userInfo['is_agree'] = 1;
           }else{
               $userInfo['is_agree'] = 0;
           }
           if ($request->userInfo['id'] == $param['id']){
               $userInfo['is_agree'] = 1;
           }
            $followUser = new FollowUser();
            $is_follow = $followUser->where([
                'uid' => $request->userInfo['id'],
                'follow_uid' => $param['id'],
            ])->find();
            if ($is_follow) {
                $userInfo['is_follow'] = 1;
            } else {
                $userInfo['is_follow'] = 0;
            }
            if (empty($userInfo)) {
                return error('用户不存在');
            }
        } else {
            $userInfo = $request->userInfo;
            $userInfo['is_agree'] = 1;
        }
        $amountLogModel = new AmountLog();
        $amountTotal = $amountLogModel->where(['uid' => $userInfo['uid'], 'amount_direction' => 1])->where(['amount_type' => 2])->sum('amount');
        $amountToday = $amountLogModel->where(['uid' => $userInfo['uid'], 'amount_direction' => 1])->where(['amount_type' => 2])->where('create_time', '>', time())->sum('amount');
        $userInfo['amount_total'] = $amountTotal;
        $userInfo['amount_today'] = $amountToday;
        $userGzhModel = new UserGzh();
        $userGzh = $userGzhModel->where(['id' => $userInfo['user_gzh_id']])->find();
        // $userInfo['gzh_openid'] = $userGzh['openid'];
        $userXcxModel = new UserXcx();
        $userXcx = $userXcxModel->where(['id' => $userInfo['user_xcx_id']])->find();
        //$userInfo['xcx_openid'] = $userXcx['openid'];
        $tokenModel = new UserToken();
        $authInfo = $tokenModel->where(['uid' => $userInfo['id'], 'type' => 1])->order('effective_time', 'desc')->find();
        $url = getProtocol() . $_SERVER["HTTP_HOST"] . '/H5/index.html?invite=' . $userInfo['invite_code'] . '#/';
        $QRcode = new QRcode();
        $imageString = $QRcode->png($url, './uploads/qrcode/' . $userInfo['invite_code'] . '.png', "2", 4, 1)->entry();
        $userInfo['invite_url'] = $imageString;
        $Miniprogram = new Miniprogram();
        if ($userXcx) {
            $userInfo['invite_xcx_url'] = $Miniprogram->getwxacode($userInfo['invite_code']);
        }

        if (empty($authInfo)) {
            $jwt = new JwtService();
            //根据用户id生成token
            $token = $jwt->getToken($userInfo['id'], 30);  //获取token
            $tokenConfig = ['uid' => $userInfo['id'], 'token' => $token, 'create_time' => time(),
                'effective_time' => time() + 60 * 60 * 24 * 30, 'login_ip' => $request->ip(), 'type' => 1];  //token配置信息  //token配置信息
            $tokenModel->insert($tokenConfig);  //更新token
        } else {
            $token = $authInfo['token'];
        }
        $userInfo['token'] = $token;
        if ($userInfo['level_id'] > 1) {
            $userModel = new UserLevel();
            $userLevelInfo = $userModel->where(['uid' => $userInfo['id'], 'level_id' => $userInfo['level_id']])->find();
            $userInfo['vip_end_time'] = $userLevelInfo['end_time'];
        }
        return success('用户信息', $userInfo);
    }

    public function followUser(Request $request)
    {
        $param = $request->param();
        $userModel = new \app\common\model\User();
        $followUser = new FollowUser();
        if ($param['follow'] == 1) {
            $is_follow = $followUser->where([
                'uid' => $request->userInfo['id'],
                'follow_uid' => $param['uid'],
            ])->find();
            if ($is_follow) {
                return error('已关注');
            }
            $followUser->insert([
                'uid' => $request->userInfo['id'],
                'follow_uid' => $param['uid'],
                'create_time' => time()
            ]);
            $userModel->where(['id' => $request->userInfo['id']])->inc('follow')->update();
            $userModel->where(['id' => $param['uid']])->inc('fans')->update();
            $messageModel = new MessageTemplate();
            $xcxMessage[]['data'] = [
                'thing1' => ['value' => $request->userInfo['nickname']],
                'time2' => ['value' => date('Y-m-d H:i')],
            ];
            $xcxMessage[0]['uid'] = $param['uid'];
            $xcxMessage[0]['title'] = 'follow';
            $messageModel->sendMessage(3, $xcxMessage);
            return success('关注成功');
        } else {
            $is_follow = $followUser->where([
                'uid' => $request->userInfo['id'],
                'follow_uid' => $param['uid'],
            ])->find();
            if (empty($is_follow)) {
                return error('已取消');
            }
            $followUser->where([
                'uid' => $request->userInfo['id'],
                'follow_uid' => $param['uid'],
            ])->delete();
            $userModel->where(['id' => $request->userInfo['id']])->dec('follow')->update();
            $userModel->where(['id' => $param['uid']])->dec('fans')->update();
            return success('操作成功');
        }
    }

    public function myFollowUser(Request $request)
    {
        $param = $request->param();
        $limit = 10;
        $start = 0;
        $where = [];
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        if (isset($param['nickname']) && !empty($param['nickname'])) {
            $where = ['u.nickname', 'like', '%' . $param['nickname'] . '%'];
        }
        $followUser = new FollowUser();
        $list = $followUser->alias('fu')
            ->where(['uid' => $request->userInfo['id']])
            ->where($where)
            ->leftJoin('user u', 'fu.follow_uid = u.id')
            ->limit($start, $limit)
            ->field('u.*,fu.create_time')
            ->order('fu.create_time','desc')
            ->select()->toArray();
        $count = $followUser->alias('fu')
            ->where(['uid' => $request->userInfo['id']])
            ->where($where)
            ->leftJoin('user u', 'fu.follow_uid = u.id')
            ->count();
        return success('我的关注', ['list' => $list, 'count' => $count]);
    }

    public function myFansUser(Request $request)
    {
        $param = $request->param();
        $limit = 10;
        $start = 0;
        $where = [];
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        if (isset($param['nickname']) && !empty($param['nickname'])) {
            $where[] = ['u.nickname', 'like', '%' . $param['nickname'] . '%'];
        }
        $followUser = new FollowUser();
        $list = $followUser->alias('fu')
            ->where(['follow_uid' => $request->userInfo['id']])
            ->leftJoin('user u', 'fu.uid = u.id')
            ->where($where)
            ->limit($start, $limit)
            ->order('fu.create_time','desc')
            ->field('u.*,fu.create_time')
            ->select()->toArray();
        $count = $followUser->alias('fu')
            ->where(['follow_uid' => $request->userInfo['id']])
            ->where($where)
            ->leftJoin('user u', 'fu.uid = u.id')
            ->count();
        return success('我的粉丝', ['list' => $list, 'count' => $count]);
    }

    public function visitUser(Request $request)
    {
        $param = $request->param();
        $data = [
            'uid' => $request->userInfo['id'],
            'visit_uid' => $param['uid'],

        ];
        $visitLogModel = new VisitLog();
        $visitLogInfo = $visitLogModel->where($data)->find();
        if ($visitLogInfo) {
            $visitLogModel->where(['id' => $visitLogInfo['id']])->inc('num')->update(['update_time' => time(), 'is_view' => 0]);
        } else {
            $data['create_time'] = time();
            $data['is_view'] = 0;
            $data['num'] = 1;
            $data['update_time'] = time();
            $visitLogModel->insert($data);
        }
        return success('成功');
    }

    public function myVisitLog(Request $request)
    {
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where = [];
        if (isset($param['nickname']) && !empty($param['nickname'])) {
            $where[] = ['u.nickname', 'like', '%' . $param['nickname'] . '%'];
        }
        $visitLogModel = new VisitLog();
        $list = $visitLogModel->alias('vl')
            ->where(['uid' => $request->userInfo['id']])
            ->leftJoin('user u', 'vl.visit_uid = u.id')
            ->where($where)
            ->limit($start, $limit)
            ->field('u.*,vl.create_time,vl.num,vl.update_time,vl.uid,vl.visit_uid')
            ->select()->toArray();
        $followUserModel = new FollowUser();

        foreach ($list as $key => $value) {
            $isFollowMe = $followUserModel->where(['follow_uid' => $request->userInfo['id']])
                ->where(['uid' => $value['visit_uid']])->find();
            if ($isFollowMe) {
                $list[$key]['is_follow_me'] = 1;
            } else {
                $list[$key]['is_follow_me'] = 0;
            }
            $isFollowHe = $followUserModel->where(['follow_uid' => $value['visit_uid']])
                ->where(['uid' => $request->userInfo['id']])->find();
            if ($isFollowHe) {
                $list[$key]['is_follow_he'] = 1;
            } else {
                $list[$key]['is_follow_he'] = 0;
            }
        }
        $count = $visitLogModel->alias('vl')
            ->where(['uid' => $request->userInfo['id']])
            ->where($where)
            ->leftJoin('user u', 'vl.visit_uid = u.id')
            ->count();
        return success('我看过谁', ['list' => $list, 'count' => $count]);
    }

    public function visitMeLog(Request $request)
    {
        $param = $request->param();
        $limit = 10;
        $start = 0;
        $where = [];
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        if (isset($param['nickname']) && !empty($param['nickname'])) {
            $where[] = ['u.nickname', 'like', '%' . $param['nickname'] . '%'];
        }
        $visitLogModel = new VisitLog();
        $list = $visitLogModel->alias('vl')
            ->where(['visit_uid' => $request->userInfo['id']])
            ->where($where)
            ->leftJoin('user u', 'vl.uid = u.id')
            ->limit($start, $limit)
            ->field('u.*,vl.create_time,vl.num,vl.update_time,vl.uid,vl.visit_uid')
            ->select()->toArray();
        $count = $visitLogModel->alias('vl')
            ->where(['visit_uid' => $request->userInfo['id']])
            ->where($where)
            ->leftJoin('user u', 'vl.uid = u.id')
            ->count();
        $followUserModel = new FollowUser();
        foreach ($list as $key => $value) {
            $isFollowMe = $followUserModel->where(['follow_uid' => $request->userInfo['id']])
                ->where(['uid' => $value['uid']])->find();
            if ($isFollowMe) {
                $list[$key]['is_follow_me'] = 1;
            } else {
                $list[$key]['is_follow_me'] = 0;
            }
            $isFollowHe = $followUserModel->where(['follow_uid' => $value['uid']])
                ->where(['uid' => $request->userInfo['id']])->find();
            if ($isFollowHe) {
                $list[$key]['is_follow_he'] = 1;
            } else {
                $list[$key]['is_follow_he'] = 0;
            }
        }
        $visitLogModel->where(['visit_uid' => $request->userInfo['id']])->update(['is_view' => 1]);
        return success('谁看过我', ['list' => $list, 'count' => $count]);
    }

    /**
     * 直推用户
     */
    public function fans(Request $request)
    {
        $param = $request->param();
        $userModel = new \app\common\model\User();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where[] = ['pid', '=', $request->userInfo['id']];
        if (isset($param['name']) && !empty($param['name'])) {
            $where[] = ['phone|nickname', 'like', '%' . $param['name'] . '%'];
        }
        if (isset($param['start_time']) && !empty($param['start_time'])) {
            $where[] = ['create_time', '>=', strtotime($param['start_time'])];
        }
        if (isset($param['end_time']) && !empty($param['end_time'])) {
            $where[] = ['create_time', '<=', strtotime($param['end_time'])];
        }
        $userList = $userModel->where($where)
            ->field('id,avatar,nickname,phone,create_time')->limit($start, $limit)->select()->toArray();
        $count = $userModel->where($where)->count();
        if ($userList) {
            $userCommissionModel = new UserCommission();
            $userIds = array_column($userList, 'id');
            $userCommission = $userCommissionModel
                ->where('trigger_uid', 'in', $userIds)
                ->field('trigger_uid,sum(amount) as amount')
                ->where('receive_uid', '=', $request->userInfo['id'])
                ->group('trigger_uid')->select()->toArray();
            $userCommissionById = [];
            if ($userCommission) {
                $userCommissionById = array_column($userCommission, null, 'trigger_uid');
            }
            foreach ($userList as $key => $item) {
                if (array_key_exists($item['id'], $userCommissionById)) {
                    $userList[$key]['amount'] = $userCommissionById[$item['id']]['amount'];
                } else {
                    $userList[$key]['amount'] = 0;
                }
            }
        }
        return success('直推用户列表', ['list' => $userList, 'count' => $count]);
    }

    /**
     * 间推用户
     */
    public function secondFans(Request $request)
    {
        $param = $request->param();
        $userModel = new \app\common\model\User();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $userList = $userModel->where(['pid' => $request->userInfo['id']])->field('id,nickname,phone,create_time,avatar')->limit($start, $limit)->select()->toArray();
        $count = 0;
        $secondFans = [];
        if ($userList) {
            $userIds = array_column($userList, 'id');
            $userById = array_column($userList, null, 'id');
            $where[] = ['pid', 'in', $userIds];
            if (isset($param['name']) && !empty($param['name'])) {
                $where[] = ['phone|nickname', 'like', '%' . $param['name'] . '%'];
            }
            if (isset($param['start_time']) && !empty($param['start_time'])) {
                $where[] = ['create_time', '>=', strtotime($param['start_time'])];
            }
            if (isset($param['end_time']) && !empty($param['end_time'])) {
                $where[] = ['create_time', '<=', strtotime($param['end_time'])];
            }
            $secondFans = $userModel->where($where)->field('id,nickname,avatar,phone,pid,create_time')->limit($start, $limit)->select()->toArray();
            $count = $userModel->where($where)->count();
            if ($secondFans) {
                $secondFansIds = array_column($secondFans, 'id');
                $userCommissionModel = new UserCommission();
                $userCommission = $userCommissionModel
                    ->where('trigger_uid', 'in', $secondFansIds)
                    ->field('trigger_uid,sum(amount) as amount')
                    ->where('receive_uid', '=', $request->userInfo['id'])
                    ->group('trigger_uid')->select()->toArray();
                $userCommissionById = [];
                if ($userCommission) {
                    $userCommissionById = array_column($userCommission, null, 'trigger_uid');
                }
                foreach ($secondFans as $key => $item) {
                    if (array_key_exists($item['id'], $userCommissionById)) {
                        $secondFans[$key]['amount'] = $userCommissionById[$item['id']]['amount'];
                    } else {
                        $secondFans[$key]['amount'] = 0;
                    }
                    $secondFans[$key]['pid_nickname'] = $userById[$item['pid']]['nickname'];
                    $secondFans[$key]['pid_avatar'] = $userById[$item['pid']]['avatar'];
                    $secondFans[$key]['pid_phone'] = $userById[$item['pid']]['phone'];
                }
            }
        }
        return success('间推用户', ['list' => $secondFans, 'count' => $count]);
    }

    public function distributionLog(Request $request)
    {
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where = [];
        if (isset($param['start_time']) && !empty($param['start_time'])) {
            $where[] = ['uc.create_time', '>=', strtotime($param['start_time'])];
        }
        if (isset($param['end_time']) && !empty($param['end_time'])) {
            $where[] = ['uc.create_time', '<=', strtotime($param['end_time'])];
        }
        $userCommissionModel = new UserCommission();
        $list = $userCommissionModel->alias('uc')
            ->leftJoin('user u', 'uc.trigger_uid = u.id')
            ->where(['receive_uid' => $request->userInfo['id']])
            ->where($where)
            ->limit($start, $limit)
            ->field('uc.*,u.nickname,u.phone,u.avatar')
            ->select()->toArray();
        $count = $userCommissionModel->alias('uc')
            ->leftJoin('user u', 'uc.trigger_uid = u.id')
            ->where(['receive_uid' => $request->userInfo['id']])
            ->where($where)
            ->limit($start, $limit)
            ->field('uc.*,u.nickname,u.phone,u.avatar')
            ->count();
        return success('分销列表', ['list' => $list, 'count' => $count]);
    }

    public function amountLog(Request $request)
    {
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where = [];
        if (isset($param['start_time']) && !empty($param['start_time'])) {
            $where[] = ['create_time', '>=', strtotime($param['start_time'])];
        }
        if (isset($param['end_time']) && !empty($param['end_time'])) {
            $where[] = ['create_time', '<=', strtotime($param['end_time'])];
        }
        if (isset($param['amount_type']) && !empty($param['amount_type'])) {
            $where[] = ['amount_type', '=', strtotime($param['amount_type'])];
        }
        if (isset($param['operation_source']) && !empty($param['operation_source'])) {
            $where[] = ['operation_source', '=', strtotime($param['operation_source'])];
        }
        $amountModel = new AmountLog();
        $list = $amountModel
            ->where(['uid' => $request->userInfo['id']])
            ->where($where)
            ->limit($start, $limit)
            ->order('create_time', 'desc')
            ->select()->toArray();
        $count = $amountModel
            ->where(['uid' => $request->userInfo['id']])
            ->where($where)
            ->limit($start, $limit)
            ->field('uc.*,u.nickname,u.phone,u.avatar')
            ->count();
        return success('分销列表', ['list' => $list, 'count' => $count]);
    }

    public function authentication(Request $request)
    {
        $param = $request->param();
        $data = [
            'real_name' => $param['real_name'],
            'nickname' => $param['nickname'],
            'id_card_front' => $param['id_card_front'],
            'id_card_back' => $param['id_card_back'],
            'is_authentication' => 1,
            'id_card_number' => $param['id_card_number'],
            'height' => $param['height'],
            'school' => $param['school'],
            'img' => $param['img'],
            'label' => $param['label'],
            'birthday' => $param['birthday'],
            'sex' => $param['sex'],
            'introduce' => $param['introduce'],
            'authentication_img' => $param['authentication_img'],
            'cover_image' => $param['cover_image'],
            'age' => $param['age'],
            'background_img' => $param['background_img'],
            'phone'  =>  $param['phoneNumber'],

        ];
      if (isset($param['sms_code']) && !empty($param['sms_code'])){
            $smsMessageModel = new SmsMessage();
            $smsMessageInfo = $smsMessageModel->where(['phone' => $param['phoneNumber'], 'code' => $param['sms_code'],'is_use' => 0])
                ->order('create_time', 'desc')->find();
            if (empty($smsMessageInfo)) {
                return error('无效验证码');
            }
            if ( time() > $smsMessageInfo['effective_time']   ) {
                return error('验证码过期');
            }
            $smsMessageModel->where(['id' => $smsMessageInfo['id']])->update(['is_use' => 1]);
        }
        if (isset($param['avatar']) && !empty($param['avatar'])) {
            $data['avatar'] = $param['avatar'];
        }
        if (isset($param['speech']) && !empty($param['speech'])) {
            $data['speech'] = $param['speech'];
        }
        $userModel = new \app\common\model\User();
        $userModel->where(['id' => $request->userInfo['id']])->update($data);
        return success('等待审核');
    }

    public function nearUser(Request $request)
    {
        $param = $request->param();
        $latitude = $param['dimension'];
        $longitude = $param['longitude'];
        // 计算距离
        $raidus = $param['distance']; // 如果距离是米，需要转换成公里
        $userModel = new \app\common\model\User();
        // 查询用户模型
        $PI = 3.14159265;
        $degree = (24901 * 1609) / 360.0;
        $dpmLat = 1 / $degree;
        $radiusLat = $dpmLat * $raidus;
        $minLat = $latitude - $radiusLat;
        $maxLat = $latitude + $radiusLat;
        $mpdLng = $degree * cos($latitude * ($PI / 180));
        $dpmLng = 1 / $mpdLng;
        $radiusLng = $dpmLng * $raidus;
        $minLng = $longitude - $radiusLng;
        $maxLng = $longitude + $radiusLng;
        $condition[] = ['dimension', '>=', $minLat];
        $condition[] = ['dimension', '<=', $maxLat];
        $condition[] = ['longitude', '>=', $minLng];
        $condition[] = ['longitude', '<=', $maxLng];
        //  $condition[] = ['id', '<>', $request->userInfo['id']];
        $list = $userModel->where($condition)->where(['is_authentication' => 2])->select()->toArray();
        $followUserModel = new  FollowUser();
        foreach ($list as $key => $value) {
            $isFollowMe = $followUserModel->where(['follow_uid' => $request->userInfo['id']])
                ->where(['uid' => $value['id']])->find();
            if ($isFollowMe) {
                $list[$key]['is_follow_me'] = 1;
            } else {
                $list[$key]['is_follow_me'] = 0;
            }
            $isFollowHe = $followUserModel->where(['follow_uid' => $value['id']])
                ->where(['uid' => $request->userInfo['id']])->find();
            if ($isFollowHe) {
                $list[$key]['is_follow_he'] = 1;
            } else {
                $list[$key]['is_follow_he'] = 0;
            }
        }
        $count = $userModel->where($condition)->where(['is_authentication' => 2])->count();
        return success('用户列表', ['list' => $list, 'count' => $count]);
        // 返回查询结果
    }

    public function userList(Request $request)
    {
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where = [];
        $userModel = new \app\common\model\User();
        // $where[] = ['id', '<>', $request->userInfo['id']];
        if (isset($param['name']) && !empty($param['name'])) {
            $where[] = ['nickname', 'like', '%' . $param['name'] . '%'];
        }
        $list = $userModel->where($where)->where(['is_authentication' => 2])->limit($start, $limit)->order('sort', 'asc')->select()->toArray();
        $followUserModel = new  FollowUser();
        foreach ($list as $key => $value) {
            if(isset($param['id']) && !empty($param['id'])){
                   $isFollowMe = $followUserModel->where(['follow_uid' =>$param['id']])
                ->where(['uid' => $value['id']])->find();
            if ($isFollowMe) {
                $list[$key]['is_follow_me'] = 1;
            } else {
                $list[$key]['is_follow_me'] = 0;
            }
            $isFollowHe = $followUserModel->where(['follow_uid' => $value['id']])
                ->where(['uid' => $param['id']])->find();
            if ($isFollowHe) {
                $list[$key]['is_follow_he'] = 1;
            } else {
                $list[$key]['is_follow_he'] = 0;
            }
            }else{
                 $list[$key]['is_follow_me'] = 0;
                 $list[$key]['is_follow_he'] = 0;
            }
         
        }
        $count = $userModel->where($where)->where(['is_authentication' => 2])->count();
        return success('用户列表', ['list' => $list, 'count' => $count]);
    }

    public function bindUser(Request $request)
    {
        $param = $request->param();
        $redis = new  Redis();
        if (empty($param['client_id'])) {
            return success('websockt进程有误');
        }
        if ($param['type'] == 'message') {
            if (!empty($param['uid'])) {
                $redis->set($param['type'] . '_' . $param['uid'] . '_' . $request->userInfo['id'], $param['client_id']);
            }

        } else {
            $redis->set($param['type'] . '_' . $request->userInfo['id'], $param['client_id']);
            $redis->set('is_online_' . $param['client_id'], $request->userInfo['id']);
        }


        return success('绑定成功');
    }

    /**
     * 用户聊天列表
     */
    public function chatList(Request $request)
    {
        $param = $request->param();
        $userChatModel = new UserChat();
        $userMessageModel = new UserMessage();
        $where[] = ['uid|receive_uid', '=', $request->userInfo['id']];
        /*  if (isset($param['limit']) && !empty($param['limit'])) {
              $limit = $param['limit'];
          }
          if (isset($param['page']) && !empty($param['page'])) {
              $start = ($param['page'] - 1) * $limit;
          }*/
        if (isset($param['nickname']) && !empty($param['nickname'])) {
            $where[] = ['u.nickname|ru.nickname', 'like', '%' . $param['nickname'] . '%'];
        }
        $list = $userChatModel->alias('uc')
            ->where($where)
            ->leftJoin('user u', 'uc.receive_uid = u.id')
            ->leftJoin('user ru', 'uc.uid = ru.id')
            ->order('uc.update_time', 'desc')
            ->field('uc.uid,
            uc.receive_uid,uc.is_remove,
             uc.update_time,
            ru.id as ru_id, ru.nickname as ru_nickname,ru.avatar as ru_avatar,ru.age as ru_age,ru.sex as ru_sex,
            uc.create_time,uc.id,
            u.nickname ,u.avatar ,u.age ,u.sex ,u.id as uuid')
            ->select()->toArray();
        $followUserModel = new  FollowUser();
        $count = $userChatModel->alias('uc')
            ->where($where)
            ->leftJoin('user u', 'uc.receive_uid = u.id')
            ->leftJoin('user ru', 'uc.uid = ru.id')
            ->count();
        $userListId = [];
        if ($list) {
            foreach ($list as $key => $value) {
                if ($request->userInfo['id'] == $value['uid']) {
                    $isFollowMe = $followUserModel->where(['follow_uid' => $value['uid']])
                        ->where(['follow_uid' => $value['receive_uid']])->find();
                    if ($isFollowMe) {
                        $list[$key]['is_follow_me'] = 1;
                    } else {
                        $list[$key]['is_follow_me'] = 0;
                    }
                } else {
                    $isFollowMe = $followUserModel->where(['follow_uid' => $value['receive_uid']])
                        ->where(['follow_uid' => $value['uid']])->find();
                    if ($isFollowMe) {
                        $list[$key]['is_follow_me'] = 1;
                    } else {
                        $list[$key]['is_follow_me'] = 0;
                    }
                }
                if (in_array($value['uid'] . '_' . $value['receive_uid'], $userListId) || in_array($value['receive_uid'] . '_' . $value['uid'], $userListId)) {
                    unset($list[$key]);
                    continue;
                } else {
                    $userListId[] = $value['uid'] . '_' . $value['receive_uid'];
                }
                if ($request->userInfo['id'] == $value['uid'] && $value['is_remove'] == 1) {
                    unset($list[$key]);
                }
            }
        }

        $list = array_values($list);
        foreach ($list as $keys => $item) {
            /*    if ($item['receive_uid'] == $request->userInfo['id']){*/
            $meSendMessage = $userMessageModel->where(['send_uid' => $item['uid']])
                ->where(['receive_uid' => $item['receive_uid']])
                ->order('create_time', 'desc')->find();
            $list[$keys]['message'] = $meSendMessage;
            $list[$keys]['message_count'] = $userMessageModel->where(['send_uid' => $item['uid']])
                ->where(['receive_uid' => $request->userInfo['id']])->where(['is_read' => 0])
                ->count();
        }
        return success('成功', ['list' => $list, 'count' => $count]);

    }

    /*
     * 和用户的消息记录
     */
    public function chatMessageList(Request $request)
    {
        $param = $request->param();
        $userMessageModel = new UserMessage();
        $limit = 10;
        $start = 0;
        $where[] = ['send_uid|receive_uid', '=', $request->userInfo['id']];
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        if (isset($param['uid']) && !empty($param['uid'])) {
            $where[] = ['send_uid|receive_uid', '=', $param['uid']];

        }
        $list = $userMessageModel->alias('um')
            ->leftJoin('user u', 'um.send_uid  = u.id')->where($where)
            ->leftJoin('user ru', 'um.receive_uid  = u.id')
            ->field('um.*,u.nickname as send_nickname,u.avatar as send_avatar,ru.nickname as receive_nickname,ru.avatar as receive_avatar')
            ->limit($start, $limit)->order('create_time', 'desc')->select()->toArray();
        $count = $userMessageModel->where($where)->limit($start, $limit)->count();

        return success('成功', ['list' => $list, 'count' => $count]);
    }

    public function removeChat(Request $request)
    {
        $param = $request->param();
        $userChatModel = new UserChat();
        $userChatInfo = $userChatModel->where(['id' => $param['id']])->find();
        if ($userChatInfo['receive_uid'] == $request->userInfo['id']) {
            $userChatModel->where(['uid' => $userChatInfo['receive_uid'], 'receive_uid' => $userChatInfo['uid']])->update(['is_remove' => 1]);
            $userChatModel->where(['receive_uid' => $userChatInfo['receive_uid'], 'uid' => $userChatInfo['uid']])->delete();
        } else {
            $userChatModel->where(['uid' => $userChatInfo['receive_uid'], 'receive_uid' => $userChatInfo['uid']])->delete();
            $userChatModel->where(['receive_uid' => $userChatInfo['receive_uid'], 'uid' => $userChatInfo['uid']])->update(['is_remove' => 1]);
        }

        return success('成功');

    }

    public function readChatMessage(Request $request)
    {
        $param = $request->param();
        $userChatModel = new UserMessage();
        $userChatModel->where(['send_uid' => $param['uid'], 'receive_uid' => $request->userInfo['id']])->update(['is_read' => 1]);
        return success('成功');
    }

    /**
     * @param Request $request
     * @return \think\response\Json 把通知消息设为已读
     */
    public function readNoticeMessage(Request $request)
    {
        $param = $request->param();
        $noticeMessageModel = new NoticeMessage();
        if (isset($param['type']) && $param['type'] == 2) {
            $where[] = ['type', 'in', [1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15]];
        } else {
            $where[] = ['type', '=', 7];
        }
        $noticeMessageModel->where(['receive_uid' => $request->userInfo['id']])->where($where)->update(['is_read' => 1]);
        return success('成功');
    }

    /**
     *通知消息
     */
    public function message(Request $request)
    {
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where[] = ['receive_uid', '=', $request->userInfo['id']];
        $where[] = ['is_read', 'in', [0, 1]];
        if (isset($param['type']) && $param['type'] == 2) {
            $where[] = ['type', 'in', [1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15]];
        } else {
            $where[] = ['type', '=', 7];
        }
        $noticeMessageModel = new  NoticeMessage();
        $list = $noticeMessageModel->alias('n')
            ->leftJoin('user u', 'n.uid  = u.id')
            ->leftJoin('service s', 'n.service_id  = s.id')
            ->leftJoin('dazi d', 'n.dazi_id  = d.id')
            ->leftJoin('circle c', 'n.circle_id  = c.id')
            ->leftJoin('circle_comment cc', 'n.comment_id  = cc.id')
            ->field('n.*,u.nickname,u.avatar,s.title as service_title,d.title as dz_title,
            c.title as circle_title ')
            ->order('n.create_time', 'desc')
            ->where($where)
            ->limit($start, $limit)
            ->select()->toArray();
        $followUserModel = new  FollowUser();
        foreach ($list as $key => $value) {
            $isFollowMe = $followUserModel->where(['follow_uid' => $request->userInfo['id']])
                ->where(['uid' => $value['uid']])->find();
            if ($isFollowMe) {
                $list[$key]['is_follow_me'] = 1;
            } else {
                $list[$key]['is_follow_me'] = 0;
            }
            $isFollowHe = $followUserModel->where(['follow_uid' => $value['uid']])
                ->where(['uid' => $request->userInfo['id']])->find();
            if ($isFollowHe) {
                $list[$key]['is_follow_he'] = 1;
            } else {
                $list[$key]['is_follow_he'] = 0;
            }
            $list[$key]['oneserlf_nickname'] = $request->userInfo['nickname'];
            $list[$key]['oneserlf_avatar'] = $request->userInfo['avatar'];
        }
        $count = $noticeMessageModel->alias('n')
            ->leftJoin('user u', 'n.uid  = u.id')
            ->leftJoin('service s', 'n.service_id  = s.id')
            ->leftJoin('dazi d', 'n.dazi_id  = d.id')
            ->leftJoin('circle c', 'n.circle_id  = c.id')
            ->leftJoin('circle_comment co', 'n.comment_id  = co.id')
            ->where($where)
            ->count();
        $noticeMessageModel->where($where)->update(['is_read' => 1]);
        return success('消息通知', ['list' => $list, 'count' => $count]);
    }

    public function unReadMessage(Request $request)
    {

        $noticeMessageModel = new  NoticeMessage();
        $userMessageModel = new UserMessage();
        $otherCount = $noticeMessageModel
            ->where('type', 'in', [1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15])
            ->where(['is_read' => 0])
            ->where(['receive_uid' => $request->userInfo['id']])
            ->count();
        $noticeCount = $noticeMessageModel
            ->where('type', '=', 7)
            ->where(['receive_uid' => $request->userInfo['id']])
            ->where(['is_read' => 0])
            ->count();
        $chatCount = $userMessageModel->where(['is_read' => 0])
            ->where(['receive_uid' => $request->userInfo['id']])->count();
        $otherMessage = $noticeMessageModel->alias('n')
            ->where('type', 'in', [1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15])
            ->leftJoin('user u', 'n.uid = u.id')
            ->order('n.create_time', 'desc')
            ->field('n.*,u.nickname,u.phone,u.avatar')
            ->where(['receive_uid' => $request->userInfo['id']])
            ->find();
        $noticeMessage = $noticeMessageModel
            ->where('type', '=', 7)
            ->order('create_time', 'desc')
            ->where(['receive_uid' => $request->userInfo['id']])
            ->find();
        $visitModel = new VisitLog();
        $visitUser = $visitModel
            ->alias('v')
            ->leftJoin('user u', 'v.uid = u.id')
            ->where('visit_uid', '=', $request->userInfo['id'])
            ->where(['is_view' => 0])
            ->order('v.create_time', 'desc')
            ->field('v.*,u.nickname,u.phone,u.avatar')
            ->find();
        $data['visitUser'] = $visitUser;
        $data['other_count'] = $otherCount;
        $visitCount = $visitModel
            ->where('visit_uid', '=', $request->userInfo['id'])
            ->where(['is_view' => 0])
            ->count();
        $data['visitCount'] = $visitCount;
        $data['notice_count'] = $noticeCount;
        $data['chat_count'] = $chatCount;
        $otherMessage['notice_count'] = $noticeCount;
        $noticeMessage['total_unread'] = $otherCount;
        $data['other_message'] = $otherMessage;
        $data['notice_message'] = $noticeMessage;
        return success('未读消息数量', $data);
    }

    public function gsign(Request $request)
    {
        $param = $request->param();
        $url = $param['url'];
        $offiaccount = new Offiaccount();
        $ticket = $offiaccount->getWxTicket();
        if (Config::getConfigValue('pay_type') == 1) {
            $appid = Config::getConfigValue('gzh_appid');
        } else {
            $appid = Config::getConfigValue('gzh_sp_appid');
        }
        $params = [
            'timestamp' => (string)Formatter::timestamp(),
            'noncestr' => Formatter::nonce(),
            'jsapi_ticket' => $ticket['ticket'],
            'url' => $url,
        ];
        ksort($params);
        $string = urldecode(http_build_query($params));
        $signature = sha1($string);
        $params['appId'] = $appid;
        $params['string'] = $string;
        $params['sign'] = $signature;

        return success('微信参数', $params);
    }

    public function sendMessage(Request $request)
    {
        $param = $request->param();
        $chars = '0123456789';
        $str = '';
        for ($i = 0; $i < 4; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        $accessKeyId = Config::getConfigValue('ali_duanxin_access_key_secret');//为企阿里云账号秘钥ID
        $accessKeySecret = Config::getConfigValue('ali_duanxin_access_key_id');;//秘钥

        $config = new Config(['accessKeyId' => $accessKeyId, 'accessKeySecret' => $accessKeySecret]);
        $config->endpoint = "dysmsapi.aliyuncs.com";

        $client = new \AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi($config);
        $messageTemplateModel = new MessageTemplate();
        $messageInfo = $messageTemplateModel->where(['title' => 'sms'])->where(['type' => 2])->find();
        if ($messageInfo['status'] != 1) {
            return error('后台未开启发送短信验证码');
        }
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $param['phone'],
            "signName" => $messageInfo['template_name'],    //    签名
            "templateCode" => $messageInfo['tid'],    //    模板
            "templateParam" => json_encode(['code' => $str])
        ]);
        $runtime = new RuntimeOptions([]);
        $res = $client->sendSmsWithOptions($sendSmsRequest, $runtime);
        if ($res->body->code == 'OK') {
            $smsMessageModel = new SmsMessage();
            $smsMessageModel->insert(['phone' => $param['phone'], 'create_time' => time(), 'code' => $str, 'effective_time' => time() + 300]);
            return success('发送成功');
        } else {
            return error('发送失败');
        }
    }


    public function  checkUserPhone(Request $request)
    {
        $param = $request->param();
        $check_phone_price = Config::getConfigValue('check_phone_price');
        $userModel = new \app\common\model\User();
 /*       $userInfo = $userModel->where(['id' => $param['uid']])->field('id,phone')->find();*/
        $checkUserModel = new CheckUser();
        $checkLog = $checkUserModel->where(['uid' => $request->userInfo['id'], 'check_uid' => $param['uid']])->find();
        $ratio = 0;
        $price = $check_phone_price;
        if ( $request->userInfo['level_id'] > 1){
            $ratio = Config::getConfigValue('check_phone_level_ratio');
            if ($ratio > 0){
                $price = bcdiv(bcmul($check_phone_price,$ratio,2),100,2);
            }
        }

        if (empty($checkLog)) {
            if ($request->userInfo['balance'] < $price) {
                return error('余额不足');
            }
            $time = time();
            $checkUserModel->insert([
                'uid' => $request->userInfo['id'],
                'check_uid' => $param['uid'],
                'create_time' => $time,
                'original_price' => $check_phone_price,
                'ratio' => $ratio,
                'price' => $price,
            ]);
            $id  = $checkUserModel->getLastInsID();
            if ($price> 0){
                $userModel->where(['id' => $request->userInfo['id']])->dec('balance',$price)->update();
                $amountData = [
                    'uid' =>   $request->userInfo['id'],
                    'amount' => $price,
                    'amount_type' => 1,
                    'operation_source' => 18,
                    'amount_direction' => 2,
                    'create_time' => $time,
                    'correlation_id'  => $id,
                    'ratio' => 1,
                   'original_price' =>$check_phone_price
                ];
                $amountModel = new   AmountLog();
                $amountModel->insert($amountData);
            }
        }else{
            if ($checkLog['is_agree'] == 1){
                return success('等待对方同意');
            }elseif ($checkLog['is_agree'] == 2){
                $userInfo = $userModel->where(['id' => $param['uid']])->field('id,phone')->find();
                return success('已成功获取用户信息',$userInfo);
            }else {
                if ($request->userInfo['balance'] < $check_phone_price) {
                    return error('余额不足');
                }
                $time = time();
                $checkUserModel->where(['uid' => $request->userInfo['id'], 'check_uid' => $param['uid']])
                    ->update(['create_time' => $time, 'is_agree' => 1, 'price' => $check_phone_price]);
                $id = $checkUserModel->getLastInsID();
                if ($check_phone_price > 0) {
                    $userModel->where(['id' => $request->userInfo['id']])->dec('balance', $check_phone_price)->update();
                    $amountData = [
                        'uid' => $request->userInfo['id'],
                        'amount' => $check_phone_price,
                        'amount_type' => 1,
                        'operation_source' => 18,
                        'amount_direction' => 2,
                        'create_time' => $time,
                        'correlation_id' => $id,
                        'ratio' => 1,
                        'original_price' => $check_phone_price
                    ];
                    $amountModel = new   AmountLog();
                    $amountModel->insert($amountData);
                }
            }
        }
        return success('等待对方同意');
    }

    public function checkMeUser(Request $request){
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where = [];
        if (isset($param['is_agree']) && !empty($param['is_agree'])) {
            $where[] = ['cu.is_agree','=',$param['is_agree']];
        }
        if (isset($param['nickname']) && !empty($param['nickname'])) {
            $where[] = ['u.nickname','=',$param['nickname']];
        }
        $checkUserModel = new CheckUser();
        $list = $checkUserModel
            ->alias('cu')
            ->where($where)
            ->leftJoin('user u', 'cu.uid = u.id')
            ->where(['check_uid' =>$request->userInfo['id'] ])
            ->limit($start,$limit)
            ->order('cu.create_time','desc')
            ->field('cu.*,u.nickname,u.phone,u.avatar,
            u.balance,u.sex,u.age')
            ->select()->toArray();
        foreach ($list as $key => $value){
            $list[$key]['create_time'] = date('Y-m-d H:i',$value['create_time']);
        }
        $count = $checkUserModel
            ->alias('cu')
            ->leftJoin('user u', 'cu.uid = u.id')
            ->where($where)
            ->where(['check_uid' =>$request->userInfo['id'] ])
            ->count();
        return success('申请用户',['list' => $list,'count' => $count]);
    }

    public function meCheckUser(Request $request){
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where = [];
        if (isset($param['is_agree']) && !empty($param['is_agree'])) {
            $where[] = ['cu.is_agree','=',$param['is_agree']];
        }
        if (isset($param['nickname']) && !empty($param['nickname'])) {
            $where[] = ['u.nickname','=',$param['nickname']];
        }
        $checkUserModel = new CheckUser();
        $list = $checkUserModel
            ->alias('cu')
            ->leftJoin('user u', 'cu.check_uid = u.id')
            ->where($where)
            ->where(['uid' =>$request->userInfo['id'] ])
            ->limit($start,$limit)
            ->order('cu.create_time','desc')
            ->field('cu.* ,u.nickname,u.phone,u.avatar
            ,u.balance,u.sex,u.age')
            ->select()->toArray();

        foreach ($list as $key => $value){
            $list[$key]['create_time'] = date('Y-m-d H:i',$value['create_time']);
        }
        $count = $checkUserModel
            ->alias('cu')
            ->leftJoin('user u', 'cu.check_uid = u.id')
            ->where(['uid' =>$request->userInfo['id'] ])
            ->where($where)
            ->count();
        return success('申请用户',['list' => $list,'count' => $count]);
    }

    public function agreeCheck(Request $request){
        $param = $request->param();
        $checkUserModel = new CheckUser();
        $checkUserInfo = $checkUserModel->where(['id' => $param['id']])->find();
        if ($checkUserInfo['is_agree'] != 1){
            return error('已处理');
        }
        $checkUserModel->where(['id' => $param['id']])->update(['is_agree' => $param['is_agree']]);
        if ($param['is_agree'] == 2){
            $amountModel = new AmountLog();
            $recharge_ratio = Config::getConfigValue('recharge_ratio');
            $handling_fees_amount =  bcdiv($checkUserInfo['price'],$recharge_ratio,2);
            $amountModel->where(['correlation_id'=>$param['id'] ,'create_time' => $checkUserInfo['create_time']])->update([
                'handling_fees' => $checkUserInfo['price'],'handling_fees_amount' =>$handling_fees_amount]);

        }else{
            $userModel = new \app\common\model\User();
            $userModel->where(['id' => $checkUserInfo['uid']])->inc('balance',$checkUserInfo['price'])->update();
            $amountData = [
                'uid' => $checkUserInfo['uid'] ,
                'amount' => $checkUserInfo['price'],
                'amount_type' => 1,
                'operation_source' => 19,
                'amount_direction' => 1,
                'create_time' => time(),
                'correlation_id'  => $param['id'],
                'ratio' => 1,
                'original_price' =>$checkUserInfo['price']
            ];
            $amountModel = new   AmountLog();
            $amountModel->insert($amountData);
        }
        return success('操作成功');

    }

    public function chatMessagePrice(Request $request)
    {
        $param = $request->param();
        $userMessageModel = new UserMessage();
        $limit = 10;
        $start = 0;
        $where[] = ['send_uid', '=', $request->userInfo['id']];
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        if (isset($param['uid']) && !empty($param['uid'])) {
            $where[] = ['receive_uid', '=', $param['uid']];

        }
        if (isset($param['nickname']) && !empty($param['nickname'])) {
            $where[] = ['ru.nickname', '=', $param['nickname']];

        }
        $list = $userMessageModel->alias('um')
            ->leftJoin('user u', 'um.send_uid  = u.id')->where($where)
            ->leftJoin('user ru', 'um.receive_uid  = u.id')
            ->field('um.*,u.nickname as send_nickname,u.avatar as send_avatar,ru.nickname as receive_nickname,ru.avatar as receive_avatar')
            ->limit($start, $limit)->order('create_time', 'desc')->select()->toArray();
        $count = $userMessageModel->where($where)->limit($start, $limit)->count();

        return success('成功', ['list' => $list, 'count' => $count]);
    }



    /*    public function xsign(Request $request)
        {
            $param = $request->param();
            $url = $param['url'];
            $offiaccount = new Offiaccount();
            $ticket = $offiaccount->getWxTicket();
            if (\app\common\model\Config::getConfigValue('pay_type') == 1){
                $appid = \app\common\model\Config::getConfigValue('appid');
            }else{
                $appid = \app\common\model\Config::getConfigValue('sp_appid');

            }
            $params = [
                'appId' => $appid,
                'timestamp' => (string)Formatter::timestamp(),
                'noncestr' => Formatter::nonce(),
                'jsapi_ticket' => $ticket['ticket'],
                'url' => $url,
            ];
            ksort($params);
            $string = urldecode(http_build_query($params));
            $signature = sha1($string);
            $params['appId'] =\app\common\model\Config::getConfigValue('appid');
            $params['string'] = $string;
            $params['sign'] = $signature;

            return success('微信参数', $params);
        }*/
}

